<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24">
        <h1>用户注册</h1>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="5">&nbsp; </el-col>
      <el-col :span="14">
        <el-form
          :model="empForm"
          :rules="rules"
          ref="empFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="登录名" prop="logid">
            <el-input
              placeholder="请输入登录名称"
              clearable
              v-model="empForm.logid"
              @input="checkLogid"
            ></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="logpwd">
            <el-input v-model="empForm.logpwd"></el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="logpwd1">
            <el-input v-model="empForm.logpwd1"></el-input>
          </el-form-item>

          <el-form-item label="姓名" prop="ename">
            <el-input clearable v-model="empForm.ename"></el-input>
          </el-form-item>

          <el-form-item label="入职日期" prop="hiredate">
            <el-date-picker
              v-model="empForm.hiredate"
              align="left"
              type="date"
              placeholder="选择入职日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="入职部门" prop="deptno">
            <el-select v-model="empForm.deptno" placeholder="请选择部门">
              <el-option
                v-for="dept in this.deptList"
                :key="dept.deptno"
                :label="dept.dname"
                :value="dept.deptno"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="上传头像">
            <el-upload
              class="avatar-uploader"
              :action="postImgUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('empFormRef')"
              >立即注册</el-button
            >
            <el-button @click="resetForm('empFormRef')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="5"></el-col>
    </el-row>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
export default {
  created() {
    setTimeout(async () => {
      const path = 'dept/all'
      const { data: res } = await this.$ajax.get(path)
      this.deptList = res.data
      console.log(res)
    }, 2000)
  },
  data() {
    const validateDept = (rule, value, callback) => {
      if (this.empForm.deptno === '0') callback(new Error('请选择部门名称'))
      return callback()
    }
    const validateLogid = async (rule, value, callback) => {
      const path = 'logid/isexists/' + value
      const { data: res } = await this.$ajax.get(path)
      if (res.status === 200 && res.data) {
        callback(new Error('   ' + value + '  已经被占用'))
      } else if (res.status !== 200) {
        callback(new Error('  系统故障请重试'))
      }
      return callback()
    }

    const validateLogpwd1 = async (rule, value, callback) => {
      if (this.empForm.logpwd !== this.empForm.logpwd1) {
        this.empForm.logpwd1 = ''
        callback(new Error('两次密码不一致，请重新输入'))
      }
      return callback()
    }
    return {
      //  头像图片路径
      imageUrl: '',
      postImgUrl: 'http://localhost:18888/emp/img/',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          },
          {
            text: '上个月',
            onClick(picker) {
              const date = new Date()
              date.setMonth(date.getMonth() - 1)
              date.setTime(date.getTime())
              picker.$emit('pick', date)
            }
          }
        ]
      },
      deptList: [
        {
          deptno: 10,
          dname: 'ACCOUNTING',
          loc: 'NEW YORK'
        },
        {
          deptno: 20,
          dname: 'RESEARCH',
          loc: 'DALLAS'
        },
        {
          deptno: 30,
          dname: 'SALES',
          loc: 'CHICAGO'
        },
        {
          deptno: 40,
          dname: 'OPERATIONS',
          loc: 'BOSTON'
        }
      ],
      empForm: {
        logid: '888',
        logpwd: '123456',
        logpwd1: '123456',
        ename: 'admin',
        hiredate: new Date(),
        deptno: '0'
      },
      rules: {
        logid: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
          { validator: validateLogid, trigger: 'blur' }
        ],
        logpwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        logpwd1: [{ validator: validateLogpwd1, trigger: 'blur' }],
        ename: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 36 到 8 个字符', trigger: 'blur' }
        ],

        deptno: [
          { required: true, message: '请选择部门', trigger: 'blur' },
          { validator: validateDept, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      this.postImgUrl = this.postImgUrl + this.empForm.logid
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    checkLogid(value) {
      let logid = this.empForm.logid.toLowerCase()
      logid = logid.substring(logid.length - 1)
      if ((logid >= '0' && logid <= '9') || (logid >= 'a' && logid <= 'z')) {
      } else {
        this.empForm.logid = this.empForm.logid.substring(
          0,
          this.empForm.logid.length - 1
        )
        this.$message.error(
          '登录名只能包括英文字符和数字，其它数据已经被拒绝！'
        )
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const path = 'emp'
          const { data: res } = await this.$ajax.post(path, this.empForm)
          console.log(res)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
